package com.example.aircraftwar.codes.activity;

import androidx.appcompat.app.AppCompatActivity;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.text.InputFilter;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.aircraftwar.R;
import com.example.aircraftwar.codes.goal.Record;
import com.example.aircraftwar.codes.goal.RecordAdapter;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

public class RankActivity extends AppCompatActivity {

    private List<Record> records = new ArrayList<>();
    private RecordAdapter adapter;
    private List<Record> deleteRecords = new ArrayList<>();
    private List<View> views = new ArrayList<>();

    private SharedPreferences sp;
    private SharedPreferences.Editor editor;

    Record enemyRecord;
    private String difficulty;
    private String name;
    private int score;
    boolean flag = false;
    int enemyScore;
    private String time;
    public static boolean isConnected;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_rank);

        //排行榜初始化
        Intent intent = getIntent();
        difficulty = intent.getStringExtra("difficulty");
        initGoals();
        adapter = new RecordAdapter(RankActivity.this, R.layout.goal_item, records);
        ListView listView = (ListView) findViewById(R.id.goalList);
        listView.setAdapter(adapter);

        Button delete = (Button) findViewById(R.id.deleteGoal);
        delete.setOnClickListener(view->{
            deleteGoal();
            listView.setBackgroundColor(Color.WHITE);
            adapter.notifyDataSetInvalidated();
        });
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Record record = adapter.getItem(position);
                if(deleteRecords.contains(record)){
                    view.setBackgroundColor(Color.WHITE);
                    deleteRecords.remove(record);
                    views.remove(view);
                } else {
                    view.setBackgroundColor(Color.LTGRAY);
                    deleteRecords.add(record);
                    views.add(view);
                }
            }
        });

        //显示弹出
        final EditText inputServer = new EditText(this);
        inputServer.setFilters(new InputFilter[]{new InputFilter.LengthFilter(20)});
        AlertDialog.Builder builder = new AlertDialog.Builder(RankActivity.this);
        builder.setTitle("请输入昵称以保存此次游戏成绩").setIcon(R.mipmap.icon_round).setView(inputServer)
                .setNegativeButton("取消", null);
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                name = inputServer.getText().toString();
                score = intent.getIntExtra("score",0);
                time = intent.getStringExtra("time");
                if(Objects.equals(name, "") ||name==null){
                    name = "Player";
                }
                Toast.makeText(RankActivity.this,difficulty+" "+name+" "+ score + " " + time,Toast.LENGTH_SHORT).show();
                try {
                    addGoal();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
        builder.show();
    }

    private void addGoal() throws IOException {
        Record record = new Record(name,score,time);

        if(isConnected){
            System.out.println("X");
            new Thread(){
                @Override
                public void run(){
                    String content;
                    try {
                        while(!flag){
                            if ((content = OptActivity.in.readLine()) != null){
                                System.out.println("收到服务端信息");
                                System.out.println(content);
                                String[] s = content.split(",");
                                int[] num = new int[2];
                                for(int i=0;i<2;i++){
                                    num[i] = Integer.parseInt(s[i]);
                                }
                                if(num[0]==num[1]){
                                    enemyScore = score;
                                }else if(num[0]==score){
                                    enemyScore = num[1];
                                }else {
                                    enemyScore = num[0];
                                }
                                System.out.println("转换成功");
                                enemyRecord = new Record("Enemy", enemyScore,time);
                                System.out.println("已转为所需记录");
                                flag = true;
                            }
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }.start();
            new Thread(){
                @Override
                public void run(){
                    Log.i("client", "send message to server");
                    OptActivity.writer.println(score+",");
                }
            }.start();
            //以下用while阻塞主线程，使主线程等待
            while(!flag){

            }
            records.add(enemyRecord);
            //System.out.println("Z");
        }
        records.add(record);
        sortGoalsByScore();
        displayGoals();
        saveGoals();
    }

    private void deleteGoal(){
        if(deleteRecords.size()==0){
            Toast.makeText(RankActivity.this,"请先选中需要删除的成绩",Toast.LENGTH_SHORT).show();
            return;
        }
        records.removeAll(deleteRecords);
        deleteRecords.clear();
        for(View view : views){
            view.setBackgroundColor(Color.WHITE);
        }
        views.clear();
        Toast.makeText(RankActivity.this,"删除成功",Toast.LENGTH_SHORT).show();
        sortGoalsByScore();
        displayGoals();
        saveGoals();
    }

    private void initGoals(){
        TextView rankTitle = (TextView) findViewById(R.id.rankTitle);
        Toast.makeText(RankActivity.this,difficulty,Toast.LENGTH_SHORT).show();
         rankTitle.setText("ScoreRanking");
        readGoals();
    }

    @Override
    public void onBackPressed() {
        Intent intent = new Intent(RankActivity.this,MenuActivity.class);
        finish();
        startActivity(intent);
    }

    private void saveGoals(){
        Gson gson = new Gson();
        String goals_json = gson.toJson(records);
        editor = getSharedPreferences(difficulty,MODE_PRIVATE).edit();
        editor.clear();
        editor.putString("goals",goals_json);
        editor.commit();
    }

    private void readGoals(){
        if(isConnected){
            sp = getSharedPreferences("net",MODE_PRIVATE);
        }else{
            sp = getSharedPreferences(difficulty,MODE_PRIVATE);
        }
        String goals_json = sp.getString("goals",null);
        if(null == goals_json){
            records.clear();
        } else {
            Gson gson = new Gson();
            records = gson.fromJson(goals_json,new TypeToken<List<Record>>(){}.getType());
        }
    }

    private void sortGoalsByScore(){
        records = records.stream().sorted(Comparator.comparing(Record::getScore).reversed()).collect(Collectors.toList());
        for(int i = 0; i< records.size(); i++){
            Record recordRanking = records.get(i);
            recordRanking.setRank(i+1);
        }
    }

    private void displayGoals(){
        adapter = new RecordAdapter(RankActivity.this, R.layout.goal_item, records);
        ListView listView = (ListView) findViewById(R.id.goalList);
        listView.setAdapter(adapter);
    }
}

